<?php

/*
 * 截取字符串，当字符串比较多的时候，显示字符串+...
 * $len 要截取的字符串的长度
 * $str 字符串
 * return 处理后字符串
 */
function cut_str($len, $str){
    $length = mb_strlen($str);
    if ($length > $len) {
        $str = mb_substr($str,0, $len,'utf-8').'..';
    }
    return $str;
}



/**
导出excel
 */
function createExcel($table, $filename = '订单') {
    header("Content-type: application/vnd.ms-excel");
    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename=".$filename."_".date('Y-m-d').".xls");
    header('Expires:0');
    header('Pragma:public');
    echo '<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'.$table.'</html>';
}

/**
 * 指定位置插入字符串
 * @param $str  原字符串
 * @param $i    插入位置
 * @param $substr 插入字符串
 * @return string 处理后的字符串
 */
function insertToStr($str, $i, $substr){
    //指定插入位置前的字符串
    $startstr="";
    for($j=0; $j<$i; $j++){
        $startstr .= $str[$j];
    }
    //指定插入位置后的字符串
    $laststr="";
    for ($j=$i; $j<strlen($str); $j++){
        $laststr .= $str[$j];
    }
    //将插入位置前，要插入的，插入位置后三个字符串拼接起来
    $str = $startstr . $substr . $laststr;
    //返回结果
    return $str;
}



/**
 * 读取excel表格的内容
 * @param $filename 文件的路径
 * @return array
 */
function import_excel($filename) {
    vendor("PHPExcel.Classes.PHPExcel");
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load($filename);
    $objWorksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $objWorksheet->getHighestRow();
    $highestColumn = $objWorksheet->getHighestColumn();
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $excelData = array();
    $i = 0;
    for ( $row = 2; $row <= $highestRow; $row++){
        for ($col = 0;$col < $highestColumnIndex; $col ++) {
            $excelData[$i][] = trim((string)$objWorksheet->getCellByColumnAndRow($col,$row)->getValue());
        }
        $i ++;
    }
    return $excelData;
}

/**
 * 删除目录以及目录下的文件
 * @param $path 目录的路径
 * @param bool $delDir true为删除父目录,否则不上传
 * @return bool
 */
function delDirAndFile($path, $delDir = false) {
    $handle = opendir($path);
    if ($handle) {
        while (false !== ( $item = readdir($handle) )) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir)
            return rmdir($path);
    }else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return false;
        }
    }
}


/**
 * 解压缩zip文件
 * @param $filename zip的路径
 * @param $path 要解压到的目录
 */
function get_zip_originalsize($filename, $path) {
    //先判断待解压的文件是否存在
    if(!file_exists($filename)){
        die("文件 $filename 不存在！");
    }
    $starttime = explode(' ',microtime()); //解压开始的时间

    //将文件名和路径转成windows系统默认的gb2312编码，否则将会读取不到
    $filename = iconv("utf-8","gb2312",$filename);
    $path = iconv("utf-8","gb2312",$path);
    //打开压缩包
    $resource = zip_open($filename);
    $i = 1;
    //遍历读取压缩包里面的一个个文件
    $good_id = array();//商品id
    while ($dir_resource = zip_read($resource)) {
        //如果能打开则继续
        if (zip_entry_open($resource,$dir_resource)) {
            //获取当前项目的名称,即压缩包里面当前对应的文件名
            $file_name = $path.zip_entry_name($dir_resource);

            if( strrchr($file_name,'/') == '/' ) {
                array_push($good_id,rtrim($file_name, '/'));//获取目录的名称(即商品的id)
            };

            //以最后一个“/”分割,再用字符串截取出路径部分
            $file_path = substr($file_name,0,strrpos($file_name, "/"));
            //如果路径不存在，则创建一个目录，true表示可以创建多级目录
            if(!is_dir($file_path)){
                mkdir($file_path,0777,true);
            }
            //如果不是目录，则写入文件
            if(!is_dir($file_name)){
                //读取这个文件
                $file_size = zip_entry_filesize($dir_resource);
                //最大读取6M，如果文件过大，跳过解压，继续下一个
                if($file_size<(1024*1024*6)){
                    $file_content = zip_entry_read($dir_resource,$file_size);
                    file_put_contents($file_name,$file_content);
                }else{
                    echo "<p> ".$i++." 此文件已被跳过，原因：文件过大， -> ".iconv("gb2312","utf-8",$file_name)." </p>";
                }
            }
            //关闭当前
            zip_entry_close($dir_resource);
        }
    }
    //关闭压缩包
    zip_close($resource);
    $endtime = explode(' ',microtime()); //解压结束的时间
    $thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);
    $thistime = round($thistime,3); //保留3为小数
    return true;
}


/**
 * 验证手机号是否正确
 * @param number $mobile
 */
function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}


/**
 * 验证固定是否正确
 * @param number $mobile
 */
function islandline($tel) {
    return preg_match('/^0\d{2,3}-?\d{7,8}$/', $tel) ? true : false;
}


/**
 * 验证邮箱是否正确
 * @param $email
 * @return bool
 */

function isEmail($email) {
    $check_mail="/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/";
    return preg_match($check_mail, $email) ? true : false;
}


/**
 * 下载文件
 * @param $path_name 文件的路径
 */
function download_by_path($path_name){
    ob_end_clean();
    $hfile = fopen($path_name, "rb") or die("Can not find file: $path_name");
    Header("Content-type: application/octet-stream");
    Header("Content-Transfer-Encoding: binary");
    Header("Accept-Ranges: bytes");
    Header("Content-Length: ".filesize($path_name));
    Header("Content-Disposition: attachment; filename=$path_name");
    while (!feof($hfile)) {
        echo fread($hfile, 1024);
    }
    fclose($hfile);
}


/*
 *分页的配置信息
 * $total总条数
 * $page_num每页多少条
 */
function set_page($total, $page_num) {
    $page = new \Think\Page($total,$page_num);
    page_config($page);
    return $page;
}

/*
 * 分页配置
 */
function page_config($page) {
    $page->setConfig('header', "<li class='paginate_button'><a>%TOTAL_ROW%条 %NOW_PAGE%/%TOTAL_PAGE%</a></li>");
    $page->setConfig('prev', '上一页');
    $page->setConfig('next', '下一页');
    $page->setConfig('last', '末页');
    $page->setConfig('first', '首页');
    $page->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
}

/*
 * 按照数组分页
 * $data传入的数组
 */
function array_page($data) {
    $total = count($data);
    $page = new \Think\Page($total,C('PAGE_NUM'));
    page_config($page);
    $arr = array_slice($data,$page->firstRow,$page->listRows);
    $res_arr = array(
        'page' => $page,
        'arr' => $arr
    );
    return $res_arr;
}

/*
 * 无限极分类
 * $data 要分类的二维数组
 */
function tree(&$data,$pid = 0,$count = 1) {
    global $treeList;
    foreach ($data as $key => $value){
        if($value['pid']==$pid){
            $value['Count'] = $count;
            $treeList [] = $value;
            unset($data[$key]);
            tree($data,$value['id'],$count+1);
        }
    }
    return $treeList ;
}

/*
 * $data 要排序的数组
 * 只能排到三维数组
 */
function sortCate($data )
{
    $treeList1 = array();
    foreach ($data as $key => $value)
    {
        if($value['pid'] == 0) {
            $treeList1[] = $value;
            unset($data[$key]);
        }
    }
    $treeList2 = array();
    if(!empty($treeList1)){
        foreach ($treeList1 as $ke => $val)
        {
            $treeList2[] = $val;
            foreach($data as $key_d => $val_d){
                if($val_d['pid'] == $val['id']) {
                    $treeList2[] = $val_d;
                    unset($data[$key_d]);
                }
            }
        }
    }
    $treeList3 = array();
    foreach ($treeList2 as $k => $v)
    {
        $treeList3[] = $v;
        foreach($data as $k_d => $v_d){
            if($v_d['pid'] == $v['id']) {
                $treeList3[] = $v_d;
                unset($data[$k_d]);
            }
        }
    }
    return $treeList3 ;
}

/**
 * @param int $length
 * @return int
 */
function get_order_id() {
    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

//生成验证码
function generate_code($length = 6) {
    return rand(pow(10,($length-1)), pow(10,$length)-1);
}

/*
 * 获取父类下的全部子类
 * $id父类的id
 */
function get_child_ids($id) {
    $ids = '';
    $cate =M('category')->where( array('pid' => $id) )->select();
    if ($cate) {
        foreach ($cate as $key=>$val) {
            $ids .= ','.$val['id'];
            $ids .= get_child_ids($val['id']);
        }
    }
    return $ids;
}

/*
 * 开发期打印公共函数
 * */
function pre($arr)
{
    echo "<pre style='position:absolute;top:44px;z-index:9999999;background:#000;color:#fff;font-weight:bold;'>";
    print_r($arr);
    echo "</pre>";
}

// 格式化输出导航
function treeNav($navlist ,$pid = 0){
    $arr = array();
    foreach($navlist as $v){
        if($v['parent_id'] == $pid){ // 查到对应子类则归类
            $v['subNav'] = treeNav($navlist ,$v['nav_id']);
            $arr[] = $v;
        }
    }
    return $arr;
}

// 格式化输出权限节点
function treeAuth($authlist ,$pid = 0){
    $arr = array();
    foreach($authlist as $v){
        if($v['parent_id'] == $pid){ // 查到对应子类则归类
            $v['subNode'] = treeAuth($authlist ,$v['node_id']);
            $arr[] = $v;
        }
    }
    return $arr;
}

// id获取代理姓名
function GetAgentNameById($agent_id)
{
    if($agent_id == 0){
        return "无上级";
    }
    return M("agent")->where("agent_id = $agent_id")->getField("agent_name");
}

// id获取代理品牌
function GetBrandNameById($b_id)
{
    return M("brand")->where("id = $b_id")->getField("b_name");
}

// id获取代理级别姓名
function GetRankNameById($rank_id)
{
    if($rank_id == 0){
        return "未设定";
    }
    return M("agent_rank")->where("rank_id = $rank_id")->getField("rank_name");
}

// 转整形 整数小数负数
function to_int( $str )
{
    if(preg_match("/^[-]{0,1}[0-9]+(.[0-9]*)?$/" ,$str)){
        return $str;
    }else{
        return 0;
    }
}

// 日期格式 Y-m-d
function to_date( $str )
{
    if(preg_match("/^([12][0-9]{3})-(0[1-9]|1[0-2])-(3[01]|[12]\d|0[1-9])$/" ,$str)){
        return $str;
    }else{
        return date("Y-m-d" ,time());
    }
}

// 日期格式 Y-m-d H:i:s
function to_datetime( $str )
{
    if(preg_match("/^([12][0-9]{3})-(0[1-9]|1[0-2])-(3[01]|[12]\d|0[1-9]) ([0-5]\d):([0-5]\d):([0-5]\d)$/" ,$str)){
        return $str;
    }else{
        return date("Y-m-d H:i:s" ,time());
    }
}

// 节点url格式
function nodeUrlRule( $url )
{
    if(preg_match("/^[A-Za-z0-9_]+\/[A-Za-z0-9_]+$/" ,$url)){
        return true;
    }else{
        return false;
    }
}

// 判断是否是整形
function _int( $str )
{
    if(preg_match("/^[0-9]+$/" ,$str)){
        return true;
    }else{
        return false;
    }
}

/*
 * 发送邮件
 * $address  发送给谁
 * $title    邮件标题
 * $message  邮件消息
 * $fromname 来源名字
 * */
function SendMail($address ,$title, $message ,$fromname = 'NONE')
{
    $conf = M("config")->where("conf_type = 'smtp'")->select();
    foreach($conf as $v){
        $confs[$v['conf_key']] = $v['conf_value'];
    }
    vendor("Component.Mail");
    $mail = new PHPMailer(true);
    try {
        $mail->IsSMTP();
        $mail->CharSet    = $confs['charset'];
        $mail->AddAddress($address);
        $mail->Body       = $message;
        $mail->From       = $confs['from_email'];
        $mail->FromName   = $fromname;
        $mail->Subject    = $title;
        $mail->Host       = $confs['smtp'];
        $mail->SMTPAuth   = true;
        $mail->Port       = $confs['port'];
        $mail->SMTPSecure = $confs['ssl'] == 1 ? 'ssl' : '';
        $mail->Username   = $confs['loginname'];
        $mail->Password   = $confs['password'];
        $mail->IsHTML(true);
        $mail->MsgHTML($message);
        return($mail->Send());
    } catch (phpmailerException $e) {
        return $e->errorMessage();
    } catch (Exception $e) {
        return $e->getMessage();
    }
}
// 邮件测试发送
function TestSendMail($test_email ,$from_email, $smtp ,$port ,$ssl ,$loginname ,$password)
{
    $message = "当您收到这封邮件，表示SMTP配置成功！";
    vendor("Component.Mail");
    $mail = new PHPMailer(true);
    try {
        $mail->IsSMTP();
        $mail->CharSet    = 'UTF-8';
        $mail->AddAddress($test_email);
        $mail->Body       = $message;
        $mail->From       = $from_email;
        $mail->FromName   = "火星";
        $mail->Subject    = "这是一封测试邮件！";
        $mail->Host       = $smtp;
        $mail->SMTPAuth   = true;
        $mail->Port       = $port;
        $mail->SMTPSecure = $ssl == 1 ? 'ssl' : '';
        $mail->Username   = $loginname;
        $mail->Password   = $password;
        $mail->IsHTML(true);
        $mail->MsgHTML($message);
        return ($mail->Send());
    } catch (phpmailerException $e) {
        return ($e->errorMessage());
    } catch (Exception $e) {
        return ($e->getMessage());
    }
}

// 短信发送  $address 1 南方节点  2 北方节点
function sendSms($mobile ,$msg, $address = 1)
{
    //公共参数(帐号,密码,url地址)
    vendor("Component.SmsSend");
    if($address == 1){
        $url = 'http://api01.monyun.cn:7901/sms/v2/std/';
    }else{
        $url = 'http://api02.monyun.cn:7901/sms/v2/std/';
    }
    $smsSendConn = new SmsSendConn($url);
    $userid = M("config")->where("conf_key = 'userid' AND conf_type = 'sms'")->getField("conf_value");
    $pwd = M("config")->where("conf_key = 'pwd' AND conf_type = 'sms'")->getField("conf_value");
    $data = array(
        'userid' => $userid,
        'pwd' => $pwd,
        'mobile' => $mobile,
        'content' => $msg,
    );
    try {
        $result = $smsSendConn->singleSend($data);
        if ($result['result'] === 0) {
            return true;
        } else {
            // 发送失败返回错误码
            return $result['result'];
        }
    }catch (Exception $e) {
        // 输出捕获的异常消息，请根据实际情况，添加异常处理代码
        return $e->getMessage();
    }
}

/**
 * $string 明文或密文
 * $operation 加密ENCODE或解密DECODE
 * $key 密钥
 * $expiry 密钥有效期
 */
function InvitationCode()
{
    return rand(1000000 ,9999999);
}

// 验证是否是手机号
function is_mobile( $mobile )
{
    if(!preg_match("/^0?1[3|4|5|8|7][0-9]\d{8}$/" ,$mobile)){
        return false;
    }
    return true;
}

// 查询当前代理所代理的所有品牌
function get_agent_brands( $agent_id )
{
    $self_brands = M("agent_brand")
        ->where("agent_id = %d" ,array($agent_id))
        ->field("brand_id")
        ->select();
    $selfBrands = array();
    foreach($self_brands as $val){
        $selfBrands[] = $val["brand_id"];
    }
    return $selfBrands;
}

// 代理添加单个品牌
function add_agent_brand( $agent_id ,$brand_id)
{
    return M("agent_brand")->add(array(
        "agent_id" => $agent_id,
        "brand_id" => $brand_id
    ));
}

// 查询某个代理的某个品牌是否有预存款
function get_agent_brand_money($agent_id ,$brd)
{
    $brand_money = M("agent_brand")
        ->where("agent_id = $agent_id AND brand_id = $brd")
        ->getField("user_money");
    // 存在预存款
    if($brand_money > 0){
        return $brand_money;
    }else{
        return 0;
    }
}

// 日志
function wlm_write_log($agent_id ,$content ,$amt ,$do_type)
{
    $surplus = M("agent")->where("agent_id = %d",array($agent_id))->getField("money");
    return M("amt_change")->add(array(
        "amt_remark" => $content,
        "agent_id" => $agent_id,
        "amt" => $amt,
        "surplus" => $surplus,
        "amt_type" => $do_type,
        "change_time" => date("Y-m-d H:i:s"),
//        "shop_id"=>session("shop_id"),
    ));
}

// 获取当前页面url参数
function get_url_params()
{
    $params = parse_url($_SERVER['REQUEST_URI']);
    $url_params = explode("&" ,$params['query']);
    $not_params = array("m" ,"c" ,"a");
    $params_rs = array();
    foreach($url_params as $key => $val){
        $str_params = explode("=" ,$val);
        $param_key = strtolower($str_params[0]);
        if(!in_array($param_key ,$not_params)){
            $params_rs[] = $val;
        }
    }
    return implode("@" ,$params_rs);
}

/**
 * 获取url 中的各个参数  类似于 pay_code=alipay&bank_code=ICBC-DEBIT
 * @param type $str
 * @return type
 */
function parse_url_param($str){
    $data = array();
    $str = explode('?',$str);
    $str = end($str);
    $parameter = explode('&',$str);
    foreach($parameter as $val){
        $tmp = explode('=',$val);
        $data[$tmp[0]] = $tmp[1];
    }
    return $data;
}

// 参数解析
function pre_params( $params)
{
    $where = array();
    if($params != ''){
        $params_arr = explode("@" ,$params);
        foreach($params_arr as $val){
            $param = explode("=" ,$val);
            $where[$param[0]] = $param[1];
        }
    }
    return $where;
}

// 更新代理层级关系
function update_rank( $rank_id)
{
    $rank_brand_id = M("agent_rank")->where("rank_id = $rank_id")->getField("brand_id");
    // 查询所有级别
    $ranks = M("agent_rank")->where("rank_status = 1 AND brand_id = $rank_brand_id")->order("rank_grade ASC")->select();
    $level = 1;
    foreach($ranks as $rank){
        if($rank['rank_grade'] != $level){
            M("agent_rank")->where("rank_id = ".$rank['rank_id'])->save(array("rank_grade" => $level));
        }
        $level += 1;
    }
    M("agent_rank")->where("rank_status = 0")->save(array("rank_grade" => 0));
    return true;
}

// 审核充值后 更新用户预存款
function update_agent_account( $account_id )
{
    // 查询充值的记录 未添加的充值记录
    $account = M("agent_account")->where("account_id = $account_id AND is_add = 0")->find();
    // 判断是否通过充值
    if($account["audit_status"] == 1)
    {
        $user_money = M("agent")->where("agent_id = %d" ,array($account['agent_id']))->getField("money");
        if(!$user_money){
            // 没有选择代理品牌
            return false;
        }
        $countMoney = $user_money + $account['amount'];
        return M("agent")->where("agent_id = %d" ,array($account['agent_id']))->setField("money" ,$countMoney);
    }else{
        // 不是操作失败返回 true
        return true;
    }
}

// id获取管理姓名
function GetManagerNameById($manager_id)
{
    return M("manager")->where("id = $manager_id")->getField("name");
}

// 清理后台 runtime 缓存目录
function deldir($dir)
{
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;
            if (!is_dir($fullpath)) {
                @unlink($fullpath);
            } else {
                @deldir($fullpath);
            }
        }
    }
    closedir($dh);
}

// 更新用户某品牌预存款
function update_agent_money($agent_id ,$brand_id ,$money ,$up_t = "+")
{
    $tbl = C("DB_PREFIX") . "agent_brand";
    return M()->execute("UPDATE $tbl SET user_money = user_money $up_t $money WHERE agent_id = $agent_id AND brand_id = $brand_id");
}

//获取菜单名称
if(!function_exists("get_category"))
{
    function get_category(){
        $categories = M('category')->where(array('status'=>1))->order('id DESC')->select();
        $category = tree($categories);
        return $category;
    }
}
//获取月初时间戳
if(!function_exists("begin_This_month"))
{
    function begin_This_month()
    {
        $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
        return $beginThismonth;
    }
}
//获取月末时间戳
if(!function_exists("end_This_month"))
{
    function end_This_month()
    {
        $endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        return $endThismonth;
    }
}
//获取昨天开始的时间戳
if(!function_exists("begin_Yesterday"))
{
    function begin_Yesterday()
    {
        $beginYesterday = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        return $beginYesterday;
    }
}
//获取昨天结束的时间戳
if(!function_exists("end_Yesterday"))
{
    function end_Yesterday()
    {
        $endYesterday = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
        return $endYesterday;
    }
}

//遍历商品查询拿货价（箱件）最后输出$arr包含商品属性以及拿货价
if(!function_exists("get_unit_amt"))
{
//    参数为商品数据
    function get_unit_amt($goods)
    {
        $user_id = session('user_id');
        foreach ($goods as $key => $value) {
            $id = $value['id'];
            $new_rank_id = M('agentBrand')->where( array('brand_id'=>$value['brand_id'], 'agent_id'=>$user_id) )->getField('rank_id');
            $res = M('good_rank_price')->where(array('good_id' => $id, 'rank_id' => $new_rank_id))->find();
            $value['unit_amt'] = $res['unit_amt'];
            $value['bathc_amt'] = $res['batch_amt'];
            $arr[] = $value;
        }
        return $arr;
    }
}
//自己代理等级某个商品的拿货价
if(!function_exists("single_good_amt"))
{
//    M('good')查出来的某一条good数据
    function single_good_amt($good){
        $user_id = session('user_id');
        $new_rank_id = M('agent_brand')->where(array('brand_id'=>$good['brand_id'],'agent_id'=>$user_id))->getField('rank_id');
        $res = M('good_rank_price')->where(array('good_id'=>$good['id'],'rank_id'=>$new_rank_id))->find();
        $good['unit_amt'] = $res['unit_amt'];
        $good['batch_amt'] = $res['batch_amt'];
        return $good;
    }
}


if(!function_exists("get_price_sum")) {
    function get_price_sum($res, $property)
    {
        foreach ($res as $key => $value) {
            $price = $value[$property] - $value['freight_price'];
            $allprice[] = $price;
        }
        $pricesum = array_sum($allprice);
        return $pricesum;
    }
}

// 查询代理等级
function get_rank_grade($rank_id )
{
    return M("agent_rank")->where("rank_id = $rank_id")->getField("rank_grade");
}

// 两个代理等级比较
// 代理 $to_id 等级高于 $agent_id 返回true  否则返回false
function agent_rank_grade_pk($to_id , $agent_id)
{
    // 先查询自己代理的所有品牌
    $brands = M("agent_brand")->where("agent_id = %d" ,array($agent_id))->select();
    foreach($brands as $b_v){
        // 查询 上级是否全都代理了
        $is_agent = M("agent_brand")->where("brand_id = %d AND agent_id = %d" ,array($b_v['brand_id'] ,$to_id))->getField("rank_id");
        if(!$is_agent){ // 没有代理 返回false
            return false;
        }
        // 代理了查询等级是否符合
        $to_rank_grade = get_rank_grade( $is_agent);
        $rank_grade = get_rank_grade( $b_v['rank_id']);
        if($to_rank_grade >= $rank_grade){
            return false;
        }
    }
    return true;
}

// 代理升级更新层级关系
function upgrade_update_parent( $up_id)
{
    // 查询升级的记录
    $up_ = M("agent_upgrade")->where("up_id = %d", array($up_id))->field("agent_id,audit_manager")->find();
    return M("agent")->where("agent_id = %d", array($up_['agent_id']))->setField("parent_id" ,$up_['audit_manager']);
}

// 更新用户升级后的上下级秩序
function update_agent_by_upgrade( $up_id )
{
    // 先查询当前代理升级级别
    $up_rank = M("agent_upgrade")->where("up_id = $up_id")->find(); // 一级代理  3
    // 再查询该代理级别的 rank_grade
    $rank_grade = get_rank_grade( $up_rank['rank_id']); // 2
    $brand_id = M("agent_rank")->where("rank_id = %d", array($up_rank['rank_id']))->getField("brand_id");
    // 查询所有当前代理引荐的其他代理
    $beadd_agent = M("recommended")->where("add_agent = %d", array($up_rank['agent_id']))->field("beadd_agent")->select();
    $agent_ids = array();
    foreach($beadd_agent as $agent){
        $agent_ids[] = $agent['beadd_agent'];
    }
    // 被添加人的级别
    $rank_ids = M("agent_brand")->where("brand_id = $brand_id AND agent_id IN (".implode("," ,$agent_ids).")")->select();
    foreach($rank_ids as $rank_id){
        $rank = get_rank_grade($rank_id['rank_id']);
        if($rank > $rank_grade){
            M("agent")->where("agent_id = %d", array($rank_id['agent_id']))->setField("parent_id" ,$up_rank['agent_id']);
        }
    }
    return true;
}


//查询某个品牌的董事
function top_rank($brand_id) {
    $rank_id = M('agentRank')->where( array('brand_id'=>$brand_id, 'rank_grade'=>1) )->getField('rank_id');
    $agent_id = M('agentBrand')->where( array('brand_id'=>$brand_id, 'rank_id'=>$rank_id) )->getField('agent_id');
    $agent = M('agent')->where( array('agent_id'=>$agent_id) )->find();
    return $agent;
}

if(!function_exists("get_director"))
{
//    获取自己上面的董事id
    function get_director()
    {
        $result = M('agent_brand')->where(array('agent_id'=>session('user_id')))->find();
        $brand_id =$result['brand_id'];
        $rank_id = M('agent_rank')->where(array('brand_id'=>$brand_id,'rank_grade'=>1))->getField('rank_id');
        $director= M('agent_brand')->where(array('brand_id'=>$brand_id,'rank_id'=>$rank_id))->getField('agent_id');
        return $director;
    }
}

/*
 * 订单的总价格(不包括运费和折扣)
 * $id 订单的id
 * $uid 用户的id
 */
function top_order_price($id, $uid) {

    $order_Good = M('orderGood')->alias('a')
        ->field('a.*,b.brand_id')->join('LEFT JOIN __GOOD__ b ON a.good_id=b.id')
        ->where( array('a.order_id'=>$id) )->select();
    $sum = 0;
    foreach ($order_Good as $value) {
        $new_rank_id = M('agentBrand')->where( array('brand_id'=>$value['brand_id'], 'agent_id'=>$uid) )->getField('rank_id');
        $good_rank_price = M('goodRankPrice')->where( array('good_id'=>$value['good_id'], 'rank_id'=>$new_rank_id) )->find();
        if ($value['good_type'] == 1) {
            $sum = $sum + $good_rank_price['unit_amt'] * $value['num'];
        } else {
            $sum = $sum + $good_rank_price['batch_amt'] * $value['num'];
        }
    }
    return $sum;
}



// 判断当前人是不是最顶级（董事）
function _is_director()
{
    $rank_ids = M("agent_brand")->where("agent_id = %d" ,array(session("user_id")))->select();
    foreach($rank_ids as  $rank_id){
        $s_grade = get_rank_grade( $rank_id['rank_id']);
        if($s_grade == 1){
            return true;
        }
    }
    return false;
}
//获取输入id对象的下级代理(返回值类似$agent_brand = array('xx'=>xx,ranks),ranks是个多维数组与代理几个品牌有关)
//$agent_brand里包括 b_name agent_id brand_id rank_id rank_grade ranks(里面包含下级代理)
if(!function_exists("get_lowagent"))
{
    function get_lowagent($agent_id){
        $agent_brand = M('agent_brand')->where(array('agent_id'=>$agent_id))->select();
        foreach ($agent_brand as $key=>$value){
            $brand_id = $value['brand_id'];
            $rank_id = $value['rank_id'];
            $agent_brand[$key]['rank_grade'] = M('agent_rank')
                ->where(array('rank_id'=>$rank_id,'brand_id'=>$brand_id))->getField('rank_grade');
        }
        foreach($agent_brand as $key=>$value){
            $pid = $value['brand_id'];
            $pgrade =$value['rank_grade'];
            $agent_brand[$key]['b_name'] = M("brand")->where(array('id'=>$pid))->getField('b_name');
            $agent_brand[$key]['ranks'] = M("agent_rank")
                ->where("rank_status = 1 AND brand_id = $pid AND rank_grade>$pgrade" )
                ->order("rank_grade ASC")
                ->select();
        }
        return $agent_brand;
    }
}
//此方法同上，只是获取的不只限于agent_id下级的代理，获取的是agent_id代理的品牌下的所有代理级别
//返回值包含bran_id b_name pic info brand_id ranks(里面包含代理) agent_brand(是否是代理商品）
if(!function_exists("get_agent"))
{
    function get_agent(){
        $agent_brand = M('brand')->where(array("agent_brand"=>1,"status"=>1,"shop_id"=>session("shop_id")))->select();
        foreach ($agent_brand as $key => $val) {
            $agent_brand[$key]['brand_id'] = $val['id'];
        }
        // 查询已代理的代理级别
        foreach ($agent_brand as $key => $val) {
            $agent_brand[$key]['ranks'] = M("agent_rank")
                ->where("rank_status = 1 AND brand_id = " . $val['brand_id'])
                ->order("rank_grade ASC")
                ->select();
        }
        return $agent_brand;
    }
}

// 获取当前人所有上级代理
if (!function_exists("get_parents_agent")) {
    function get_parents_agent($self_id)
    {
        $parent_arr = array();
        $parent_id = M("agent")->where("agent_id = $self_id")->getField("parent_id");
        if ($parent_id != 0) {
            $parent_arr[] = $parent_id;
            $parent_arr = array_merge($parent_arr, get_parents_agent($parent_id));
        }
        return $parent_arr;
    }
}

//    获取openId,一定要在微信中
if(!function_exists("_get_openId")){
    function _get_openId(){
        vendor("Api.wxpay.payment.JsApiPay");
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        return $openId;
    }
}
//下单模板消息data组装
if (!function_exists("order_reminder")){
    function order_reminder($openid,$id,$url,$begin,$orderid,$money,$date,$end)
    {
        $data = array('touser' => $openid,
            'template_id' => "$id",
            'url' => $url,
            'data' => array('first' => array('value' => $begin,
                'color' => "#ff0000",
            ),
                'order' => array('value' => $orderid,
                    'color' => "#ff0000",
                ),
                'money' => array('value' => $money.'元',
                    'color' => "#ff0000",
                ),
                'time' => array('value' => $date,
                    'color' => "#ff0000",
                ),
                'remark' => array('value' => $end,
                    'color' => "#ff0000",
                ),
            )
        );
        return $data;
    }
}
//充值消息模板拼装
if (!function_exists("recharge_reminder")){
    function recharge_reminder($openid,$id,$url,$begin,$name,$type,$money,$date,$end)
    {
        $data = array('touser' => $openid,
            'template_id' => "$id",
            'url' => $url,
            'data' => array('first' => array('value' => $begin,
                'color' => "#ff0000",
            ),
                'name' => array('value' => "$name",
                    'color' => "#ff0000",
                ),
                'type' => array('value' => "$type",
                    'color' => "#ff0000",
                ),
                'money' => array('value' => $money.'元',
                    'color' => "#ff0000",
                ),
                'time' => array('value' => $date,
                    'color' => "#ff0000",
                ),
                'remark' => array('value' => $end,
                    'color' => "#ff0000",
                ),
            )
        );
        return $data;
    }
}


if(!function_exists("Template_message")) {
    function Template_message($data)
    {
        vendor("Api.wxpay.payment.JsApiPay");
        $tools = new \JsApiPay();
        $access_token = $tools->GetAccesstoken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token";
        $res = http_request($url, json_encode($data), 'json');
        return json_decode($res, true);
    }
}

//https请求（支持GET和POST）
function http_request($url, $data = null, $type)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}




// 构建支付方式html

function build_payment_html($params ,$pay_conf)
{
    $html_code = unserialize($params);
    $pay_code = unserialize($pay_conf);
    $html = "";
    foreach ($html_code as $html_k => $html_v) {
        $code = strtolower($html_v['type']);
        if ($code == "text") {
            $html .= "<div class='add-admin-ipt'><span><i>*</i>" . $html_v['label'] . "</span>".
                "<input type='text' name='" . $html_v['name'] . "' value='" . $pay_code[$html_v['name']] . "' placeholder='" . $html_v['label'] . "' class='w200'/></div>";
        }
        if ($code == "textarea") {
            $html .= "<div class='add-admin-ipt'><span><i>*</i>" . $html_v['label'] . "</span>" .
                "<textarea name='" . $html_v['name'] . "' class='txt-area w300'>" . $pay_code[$html_v['name']] . "</textarea></div>";
        }
        if ($code == "select") {
            $option = "";
            $select_status = "";
            foreach ($html_v['option'] as $option_k => $option_v) {
                if ($option_k == $pay_code[$html_v['name']]) {
                    $select_status = "selected";
                }
                $option .= "<option value='" . $option_k . "' $select_status>{$option_v}</option>";
                $select_status = "";
            }
            $html .= "<div class='add-admin-ipt'><span><i>*</i>" . $html_v['label'] . "</span>" .
                "<select name='" . $html_v['name'] . "'>$option</select></div>";
        }
    }
    return $html;
}

// 支付成功 更新数据

/**
 * 支付完成修改订单
 * @param $order_sn 订单号
 * @param $pay_code 支付方式
 * 修改订单状态 减少库存 添加日志
 */
function update_pay_status($order_sn ,$paycode)
{
    // 找出对应的订单
    $order = M('order')->where("order_id = '%s'" ,array($order_sn))->find();
    if(!$order) return false;
    //预售订单
    if ($order['is_pay'] == 1) {
        return true;
    }
    $change_order_status = M('order')->where("order_id = '%s'" ,array($order_sn))->setField("is_pay" ,1);
    if($change_order_status !== false){
        $orderGoodsArr = M('order_good')->where(array('order_id' => $order['id']))->select();
        $goods_tbl = C("DB_PREFIX")."good";
        foreach($orderGoodsArr as $goods){
            $num = $goods['num'];
            M()->execute("UPDATE $goods_tbl SET `stock` = `stock` - $num WHERE id = ".$goods["good_id"]);// 更新商品库存
            M()->execute("UPDATE $goods_tbl SET `sale_num` = `sale_num` + $num WHERE id = ".$goods["good_id"]);// 加销量
        }
        // 添加订单日志
        $pay_order = M("pay_order")->where("order_id = '%s'",array($order_sn))->find();
        if($pay_order){
            M("pay_order")->where("order_id = '%s'",array($order_sn))->save(array(
                "pay_code" => $paycode,
                "pay_name" => $pay_order["pay_name"],
                "pay_status" => 1,
                "pay_time" => time()
            ));
        }else{
            $p_name = M("payment")->where("pay_code = '%s'", array($paycode))->getField("p_name");
            M("pay_order")->add(array(
                "order_id" => $order_sn,
                "pay_code" => $paycode,
                "pay_name" => $p_name,
                "pay_status" => 1,
                "pay_time" => time()
            ));
        }
        return true;
    }else{
        return false;
    }
}

function update_recharge_status($order_sn, $amt_t, $paycode)
{
    $pay_type = M("payment")->where("pay_code = '$paycode'")->getField("p_id");
    $rgs = M('recharge')->where("r_sn = '$order_sn'")->find();
    M('agent_account')->add(array(
        "agent_id" => $rgs['agent_id'],
        "amount" => $amt_t,
        "record_time" => time(),
        "record_ip" => get_client_ip(),
        "audit_status" => 1,
        "pay_type" => $pay_type,
        "recharge_sn" => $order_sn
    ));
    $agent_tbl = C("DB_PREFIX")."agent";
    return M()->execute("UPDATE $agent_tbl SET `money` = `money` + $amt_t WHERE agent_id = ".$rgs['agent_id']);
}
/**
 * 发送短信
 * @param $mobile  手机号码
 * @param $smsParam 短信发送参数
 * @return $send_type 短信发送场景 1 注册码 2 订单推送 3 充值推送
 */
function send_sms($mobile, $smsParam, $send_type)
{
    $sms_service = M("sms_service")->where("is_open = 1")->find();
    if(!$sms_service){
        return array("status" => -1 ,'msg' => "平台未安装短信服务");
    }
    $tem = M("sms_template")->where("send_scene = $send_type AND sms_id = ".$sms_service["sms_id"])->find();
    if($sms_service["sms_code"] == "alidayu"){
        return sendSmsByAlidayu($mobile, $tem["sms_sign"], $smsParam, $tem["sms_tpl_code"]);
    }
    if($sms_service["sms_code"] == "aliyun"){
        return sendSmsByAliyun($mobile, $tem["sms_sign"], $smsParam, $tem["sms_tpl_code"]);
    }
}

/**
 * 发送短信（阿里大于）
 * @param $mobile  手机号码
 * @param $code    验证码
 * @return bool    短信发送成功返回true失败返回false
 */
function sendSmsByAlidayu($mobile, $smsSign, $smsParam, $templateCode)
{
    //时区设置：亚洲/上海
    date_default_timezone_set('Asia/Shanghai');
    //这个是你下面实例化的类
    vendor('Alidayu.TopClient');
    //这个是topClient 里面需要实例化一个类所以我们也要加载 不然会报错
    vendor('Alidayu.ResultSet');
    //这个是成功后返回的信息文件
    vendor('Alidayu.RequestCheckUtil');
    //这个是错误信息返回的一个php文件
    vendor('Alidayu.TopLogger');
    //这个也是你下面示例的类
    vendor('Alidayu.AlibabaAliqinFcSmsNumSendRequest');

    $conf = M("sms_service")->where("sms_code = 'alidayu'")->getField("sms_conf");
    $sms_c = unserialize($conf);
    $c = new \TopClient;
    //App Key的值 这个在开发者控制台的应用管理点击你添加过的应用就有了
    $c->appkey = $sms_c["appkey"];
    //App Secret的值也是在哪里一起的 你点击查看就有了
    $c->secretKey = $sms_c["secretkey"];
    //这个是用户名记录那个用户操作
    $req = new \AlibabaAliqinFcSmsNumSendRequest;
    //代理人编号 可选
    $req->setExtend("123456");
    //短信类型 此处默认 不用修改
    $req->setSmsType("normal");
    //短信签名 必须
    $req->setSmsFreeSignName($smsSign);
    //短信模板 必须
    $req->setSmsParam(json_encode($smsParam));
    //短信接收号码 支持单个或多个手机号码，传入号码为11位手机号码，不能加0或+86。群发短信需传入多个号码，以英文逗号分隔，
    $req->setRecNum("$mobile");
    //短信模板ID，传入的模板必须是在短信平台“管理中心-短信模板管理”中的可用模板。
    $req->setSmsTemplateCode($templateCode); // templateCode

    $c->format = 'json';
    //发送短信
    $resp = $c->execute($req);
    //短信发送成功返回True，失败返回false
    if ($resp && $resp->result) {
        return array('status' => 1, 'msg' => $resp->sub_msg);
    } else {
        return array('status' => -1, 'msg' => $resp->msg . ' ,sub_msg :' . $resp->sub_msg . ' subcode:' . $resp->sub_code);
    }
}

// 企业sms发送方式
function sendSmsByAliyun($mobile, $smsSign, $smsParam, $templateCode)
{
    vendor("Alidayu.SmsApi");
    $conf = M("sms_service")->where("sms_code = 'aliyun'")->getField("sms_conf");
    $sms_c = unserialize($conf);
    $sms = new \SmsApi($sms_c["accesskeyid"], $sms_c["accesskeysecret"]);
    // 请参阅 https://ak-console.aliyun.com/ 获取AK信息
    $response = $sms->sendSms(
        $smsSign, // 短信签名
        $templateCode, // 短信模板编号
        $mobile, // 短信接收者
        $smsParam  // 短信模板中字段的值  一维数组的形式
    );
    if ($response->Code == 'OK') {
        return array('status' => 1);
    } else {
        return array('status' => -1, 'msg' => $response->Message . ' code:' . $response->Code);
    }
}



/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

//对于数组重新排序 例如数组a=array([2],[3],[4]....)
function resort($array){
    $i=0;
    foreach ($array as $key => $value){
        $newarray[$i] = $value;
        $i++;
    }
    return $newarray;
}

if(!function_exists("auth_code_encode"))
{
    function auth_code_encode($ip ,$domian ,$salt)
    {
        return strtoupper(md5(base64_encode($domian. $ip) .md5($salt)));
    }
}

if(!function_exists("order_opt_log"))
{
    // 订单操作日志
    function order_opt_log($msg ,$order_sn)
    {
        $manager_id = session("manager_id");
        $shop_id = session('shop_id');
        $add_data = array(
            "order_id" => $order_sn,
            "do_info" => $msg,
            "uid" => $manager_id,
            "do_time" => date("Y-m-d H:i:s"),
            "shop_id" => $shop_id
        );
        return M('order_record')->add($add_data);
    }
}

//代理包邮
if(!function_exists("agent_is_free")){
    function agent_is_free($agent_id,$brand_id){
        $rank_id = M("agent_brand")->where(array("agent_id"=>$agent_id,"brand_id"=>$brand_id))->getField("rank_id");
        $is_free = M("agent_rank")->where(array("rank_id"=>$rank_id))->getField("is_free");
        return $is_free;
    }
}

//商品是代理商品还是普通商品
if(!function_exists("is_agent_normal")){
    function is_agent_normal($good_id){
        $brand_id = M("good")->where(array("id"=>$good_id))->getField("brand_id");
        $agent_brand = M("brand")->where(array("id"=>$brand_id))->getField("agent_brand");
        return $agent_brand;
    }
}